/*
 * Copyright ©2015-2023 Jaemon. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.cloud.alarm.dinger.core;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.cloud.alarm.dinger.config.properties.DingerProperties;
import com.cloud.alarm.dinger.core.entity.DingerRequest;
import com.cloud.alarm.dinger.core.entity.DingerResponse;
import com.cloud.alarm.dinger.core.entity.MsgType;
import com.cloud.alarm.dinger.core.entity.enums.DingerResponseCodeEnum;
import com.cloud.alarm.dinger.core.entity.enums.DingerType;
import com.cloud.alarm.dinger.core.entity.enums.MessageSubType;
import com.cloud.alarm.dinger.exception.AsyncCallException;
import com.cloud.alarm.dinger.exception.SendMsgException;
import com.cloud.alarm.dinger.support.CustomMessage;
import com.cloud.alarm.dinger.support.DingerAsyncCallback;
import com.cloud.alarm.dinger.support.DingerIdGenerator;
import com.cloud.alarm.dinger.support.client.DingerHttpClient;
import com.cloud.alarm.dinger.support.client.MediaTypeEnum;
import com.cloud.alarm.dinger.support.sign.DingerSignAlgorithm;
import com.cloud.alarm.dinger.support.sign.SignBase;
import com.cloud.alarm.dinger.utils.DingerUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor;

import static com.cloud.alarm.dinger.constant.DingerConstant.BeanName.*;


/**
 * DingTalk Robot
 *
 * @author shuai.zhou
 * @since 1.0
 */
@Slf4j
public class DingerRobot extends AbstractDingerSender {

    public DingerRobot(DingerProperties dingerProperties) {
        super(dingerProperties);
    }

    @Override
    public DingerResponse send(MessageSubType messageSubType, DingerRequest request) {
        return send(dingerProperties.getDefaultDinger(), messageSubType, request);
    }

    @Override
    public DingerResponse send(DingerRequest request) {
        return send(dingerProperties.getDefaultDinger(), MessageSubType.TEXT, request);
    }

    @Override
    public DingerResponse send(DingerType dingerType, MessageSubType messageSubType, DingerRequest request) {
        if (!messageSubType.isSupport()) {
            return DingerResponse.failed(DingerResponseCodeEnum.MESSAGE_TYPE_UNSUPPORTED);
        }
        CustomMessage customMessage = customMessage(dingerType, messageSubType);
        String msgContent = customMessage.message(request);
        request.setContent(msgContent);

        MsgType msgType = messageSubType.msgType(dingerType, request);

        return send(msgType);
    }


    /**
     * @param message 消息内容
     * @param <T>     T
     * @return 响应内容 {@link DingerResponse}
     */
    protected <T extends MsgType> DingerResponse send(T message) {
        DingerType dingerType = message.getDingerType();
        DingerIdGenerator dingerIdGenerator = SpringUtil.getBean(DINGER_ID_GENERATOR_BEAN_NAME, DingerIdGenerator.class);
        String dkid = dingerIdGenerator.dingerId();
        Map<DingerType, DingerProperties.Dinger> dingers = dingerProperties.getDingers();
        if (!(dingerProperties.isEnabled() && dingers.containsKey(dingerType))) {
            return DingerResponse.failed(dkid, DingerResponseCodeEnum.DINGER_DISABLED);
        }

        DingerConfig localDinger = getLocalDinger();
        // dinger is null? use global configuration and check whether dinger send
        boolean dingerConfig = localDinger != null;
        try {
            DingerProperties.Dinger dinger;
            if (dingerConfig) {
                dinger = new DingerProperties.Dinger();
                BeanUtils.copyProperties(localDinger, dinger);
                dinger.setAsync(localDinger.getAsyncExecute());
                dinger.setRobotUrl(dingers.get(dingerType).getRobotUrl());
            } else {
                dinger = dingers.get(dingerType);
            }

            StringBuilder webhook = new StringBuilder();
            webhook.append(dinger.getRobotUrl()).append(dinger.getTokenId());

            if (log.isDebugEnabled()) {
                log.debug("dingerId={} send message and use dinger={}, tokenId={}.", dkid, dingerType, dinger.getTokenId());
            }

            // 处理签名问题 (只支持DingTalk 或 ByteTalk)
            if (DingerUtils.isNotEmpty((dinger.getSecret()))) {
                switch (dingerType) {
                    case DINGTALK -> {
                        DingerSignAlgorithm dingTalkSignAlgorithm = SpringUtil.getBean(DINGTALK_SIGN_ALGORITHM_BEAN_NAME, DingerSignAlgorithm.class);
                        SignBase sign = dingTalkSignAlgorithm.sign(dinger.getSecret().trim());
                        webhook.append(sign.transfer());
                    }
                    case BYTETALK -> {
                        DingerSignAlgorithm byteTalkSignAlgorithm = SpringUtil.getBean(BYTETALK_SIGN_ALGORITHM_BEAN_NAME, DingerSignAlgorithm.class);
                        SignBase sign = byteTalkSignAlgorithm.sign(dinger.getSecret().trim());
                        message.signAttributes(sign);
                    }
                }
            }

            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", MediaTypeEnum.JSON.type());

            DingerHttpClient dingerHttpClient = SpringUtil.getBean(DINGER_HTTP_CLIENT_BEAN_NAME, DingerHttpClient.class);
            // 异步处理, 直接返回标识id
            if (dinger.isAsync()) {
                Executor dingerExecutor = SpringUtil.getBean(DINGER_EXECUTOR, Executor.class);
                dingerExecutor.execute(() -> {
                    try {
                        String result = dingerHttpClient.post(webhook.toString(), headers, message);
                        DingerAsyncCallback dingerAsyncCallback = SpringUtil.getBean(DINGER_ASYNC_CALLBACK_BEAN_NAME, DingerAsyncCallback.class);
                        dingerAsyncCallback.execute(dkid, result);
                    } catch (Exception e) {
                        exceptionCallback(dkid, message, new AsyncCallException(e));
                    }
                });
                return DingerResponse.success(dkid, dkid);
            }

            String response = dingerHttpClient.post(webhook.toString(), headers, message);
            log.info("dinger:【{}】send message:{}; response:{}", dingerType, JSONUtil.toJsonStr(message), JSONUtil.toJsonStr(response));
            return DingerResponse.success(dkid, response);
        } catch (Exception e) {
            exceptionCallback(dkid, message, new SendMsgException(e));
            return DingerResponse.failed(dkid, DingerResponseCodeEnum.SEND_MESSAGE_FAILED);
        }
    }

}